package it.uniroma2.structure;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;

public class If_Control extends Control{
	private ConditionControl ifCondition;
	private static int index = 1;
//	private Vector<ElseIf_Control> elseIfConditions;
//	private Else_Control elseCondition;
//	Node thenNode;
//	Node elseNode;
	
	public If_Control(){
		super();
		this.name = ifName + index;
		index++;
		this.ifCondition = new ConditionControl();
		General_Sequence_Control genSeq = new General_Sequence_Control();
		String orderSeq = this.getOrderId() + "-1";
		genSeq.setOrderId(orderSeq);
		genSeq.setFather(this);
		this.subNodes.add(genSeq);
	}
	
	public If_Control(String name){
		super();
		this.name = name;
		this.ifCondition = new ConditionControl();
		General_Sequence_Control genSeq = new General_Sequence_Control();
		String orderSeq = this.getOrderId() + "-1";
		genSeq.setOrderId(orderSeq);
		genSeq.setFather(this);
		this.subNodes.add(genSeq);
	}
	
	public If_Control(String name, ConditionControl cond){
		this(name);
		this.name = name;
		this.ifCondition = cond;
	}

	
	public void setCondition(ConditionControl cond){
		this.ifCondition = cond;
	}
	
	
	public Node addElse(){
		Else_Control elseC = new Else_Control();
		elseC.setFather(this);
		String orderSeq = this.getOrderId() + "-" + (this.subNodes.size()+1);
		elseC.setOrderId(orderSeq);
		Node seq = elseC.generateSequence();
		this.subNodes.add(elseC);
		Collections.sort(this.subNodes, new ComparetorNode());
		return seq;
	}
	
	
	public Node addElseIf(ConditionControl cc){
		ElseIf_Control elseif = new ElseIf_Control(cc);
		elseif.setFather(this);
		String orderSeq = this.getOrderId() + "-" + (this.subNodes.size()+1);
		elseif.setOrderId(orderSeq);
		Node seq = elseif.generateSequence();
		this.subNodes.add(elseif);
		Collections.sort(this.subNodes, new ComparetorNode());
		return seq;
	}
	
	
	@Override
	public String toString() {
		
		return ifTag + " name=\"" + this.name + "\"";
	}
	
	@Override
	public String toBPEL() {
		String output = "<" + this.toString() + ">\n";
		output = output + this.ifCondition.toBPEL();
		for(Node temp : this.subNodes) {
			output = output + temp.toBPEL();
		}
		return output + "</" + ifTag + ">\n";
	}

	public Node getIfSequence() {
		return this.subNodes.get(0);
	}
}
